package com.easy.lab.shixun.service.manager;

import com.alibaba.fastjson.JSON;
import com.easy.lab.shixun.api.service.GroupMemberService;
import com.easy.lab.shixun.common.constant.MessageConstant;
import com.easy.lab.shixun.common.enums.MessageTypeEnums;
import com.easy.lab.shixun.api.bo.request.MessageRequest;
import com.easy.lab.shixun.api.bo.response.MessageResponse;
import com.easy.lab.shixun.service.processor.BaseEventProcessor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 消息管理
 * @Author: https://gitee.com/wesleyOne
 * @Date: 12.07 2019
 */
@Component
@Slf4j
public class MessageManager {

    @Autowired
    private SimpMessagingTemplate messageTemplate;

    @Autowired
    private GroupMemberService groupMemberService;

    @Autowired
    private EventProcessorManager eventProcessorManager;

    /**
     * 消息核心处理
     * 根据消息类型 交由各自的处理器执行并返回结果
     * @param messageRequest 消息体
     */
    public void processMessage(MessageRequest messageRequest) {
        String type = messageRequest.getType();
        MessageTypeEnums messageType = MessageTypeEnums.getIfPresent(type);
        if (Objects.isNull(messageType)) {
            log.error("消息类型不存在 {}", type);
            return;
        }
        BaseEventProcessor processor = eventProcessorManager.getProcessorMap().get(messageType.name());
        MessageResponse messageResponse = processor.process(messageRequest);
        sendMessage(messageResponse);
    }

    /**
     * 发送消息
     * @param message   消息体
     */
    private void sendMessage(MessageResponse message) {
        log.info("sendMessage: {}", JSON.toJSON(message));
        if (Objects.nonNull(message)) {
            if (message.isToGroup()) {
                if (StringUtils.isNotBlank(message.getGroupUniqueId()) && groupMemberService.containGroup(message.getGroupUniqueId())) {
                    messageTemplate.convertAndSend(MessageConstant.BROKER_TOPIC.concat("/").concat(message.getGroupUniqueId()), message);
                }
            } else {
                String toPrincipal = message.getToPrincipal();
                if (StringUtils.isNotBlank(toPrincipal) && groupMemberService.containMember(toPrincipal)) {
                    messageTemplate.convertAndSendToUser(message.getToPrincipal(), MessageConstant.BROKER_QUEUE.concat("/").concat(message.getGroupUniqueId()), message);
                }
            }
        }
    }
}
